
package saxon.gui.view.swing;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JTextField;

/**
 *
 * @author lennyn
 */
class ChooseFilePanel extends VPanel {
	private final SwingXView view;
	private final JFileChooser fileChooser = new JFileChooser();
	private final JTextField filePathField = new JTextField(30);
	private final JButton button = new JButton("Select...");
	private ChooseFileListener listener = ChooseFileListener.getDefault();

	private File selectedFile;

	ChooseFilePanel(SwingXView view) {
		this.view = view;
		this.init();
	}
	
	void setFileSelectionMode(int mode) {
		fileChooser.setFileSelectionMode(mode);
	}
	
	void setCurrentDirectory(File dir) {
		fileChooser.setCurrentDirectory(dir);
	}
	
	void setChooseFileListener(ChooseFileListener listener) {
		this.listener = listener;
	}

	private void init() {

		button.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				showFileChooserDialog();
			}
		});
		this.add(new HPanel(filePathField, button, HPanel.glue()));
	}

	private void showFileChooserDialog() {
		int res = fileChooser.showDialog(view, "Select");
		if (res == JFileChooser.APPROVE_OPTION) {
			selectedFile = fileChooser.getSelectedFile();
			filePathField.setText(selectedFile.getAbsolutePath());
			fileChooser.setCurrentDirectory(selectedFile.getParentFile());
			listener.fileSelected(selectedFile);
		}
	}

	File getSelectedFile() {
		return selectedFile;
	}

	@Override
	public void setEnabled(boolean enabled) {
		for (Component comp: this.getComponents())
			comp.setEnabled(enabled);
	}
}
